package classes;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class DataJsonJava extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static List<User> userList = new ArrayList<User>();

	int count = 0;

	String text;
	
	public RetornaUsers retUsers = new RetornaUsers();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DataJsonJava() {
		super();
		//gera os contatos
		userList.add(new User("0","Erica", "Vicente", "erica_vicente"));
		userList.add(new User("1","Test", "Test1", "test_test"));
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processReportRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		count++;

		BufferedReader bf = request.getReader();
		String str;
		while ((str = bf.readLine()) != null) {
			System.out.println(str);
		}
		bf.close();

		processReportRequest((HttpServletRequest) request, response);
	}
	
	protected void doPut(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("do put");
	}

	private void processReportRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String text = retUsers.getJsonPapel();
		byte[] report = text.getBytes();
		response.setContentType("text/html");
		OutputStream os = response.getOutputStream();
		os.write(report);
		os.flush();
		os.close();
	}
	
	private User JSONtoUser(String str) {
		User usr = new User();

		JSONObject json = null;
		JSONObject children = null;
		try {
			json = (JSONObject)new JSONParser().parse(str);
			children = (JSONObject)new JSONParser().parse(String.valueOf(json.get("users")));
			System.out.println(children);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		usr.setId((String)children.get("id"));
		usr.setFirst((String)children.get("First"));
		usr.setLast((String)children.get("Last"));
		usr.setLogin((String)children.get("Login"));
		
		return usr;
	}
}